//接口包脚本安装 installInterface.html
app.controller('installInterfaceCtrl', function ($scope, $http, $location) {
  //页面通用初始化
  pageInit('interface');
  //左侧导航用
  menuInit($scope, $http);
  $scope.menuIndex = 3.2;

  init();
  $scope.isContinue = false;

  //执行日志全屏
  $scope.logFull = function (isLogFull) {
    if (!isLogFull)
      $(document.body).css("overflow-y", "hidden");
    else
      $(document.body).css("overflow-y", "auto");
    $scope.isLogFull = !isLogFull;
  }
  //折叠功能
  $scope.collapse = [];
  $scope.collapseFnc = function (i) {
    $scope.collapse[i] = $scope.collapse[i] ? false : true;
  };
  $scope.exAll = function () {
    for (var i in $scope.sqlListPkgs)
      $scope.collapse[i] = true;
  };

  //
  $scope.$watch('installing', function () {
    $("#path-bar").scope().installing = $scope.installing;
  }, true);

  //获取/刷新接口类型和接口列表
  function init() {
    $scope.hasTips = false;
    $http.get('/deploy/install/interface/init').then(function (response) {
      if (response.status == 200) {
        var message = response.data;
        if (message.code == 0) {
          if (message.data.errorMsg)
            $.showNotice(message.data.errorMsg, "danger");
          $scope.sqlListPkgs = message.data.packages;
          for (var i = 0; i < $scope.sqlListPkgs.length; i++) {
            for (var j = 0; j < $scope.sqlListPkgs[i].sqlList.length; j++) {
              var name = $scope.sqlListPkgs[i].sqlList[j].name.toLowerCase();
              if (name.lastIndexOf('r.sql') > -1 || name.lastIndexOf('r_view.sql') > -1) {
                $scope.hasTips = true;
                break;
              }
            }
          }
          setTimeout(function () {
            $('[data-toggle="tooltip"]').tooltip();
          }, 0);
        } else {
          $.showNotice(message.msg, "danger");
        }
      }
    }).catch(function (response) {
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  }

  //改变正在安装的sql
  function changeInstall(installingPkg, installingSql) {
    //正在安装的sql
    $scope.installingPkg = installingPkg;
    $scope.installingSql = installingSql;
  }

  //开始安装
  function startInstall(installingPkg, installingSql, isOneSql, isOnePackage) {
    if (!$scope.isContinue) {
      //清空日志
      $scope.runLogs = [];
      p = 0;
    }
    $("#installInterface-log").slideDown();
    //置为正在安装状态
    $scope.installing = true;
    //正在安装的sql
    changeInstall(installingPkg, installingSql);
    //开始轮询日志
    if (isOneSql) {
      realLog();
      $scope.interfaceInterval = setInterval(function () {
        realLog();
      }, 2000)
    } else if (isOnePackage) {
      realLog();
      schedule(installingPkg);
      $scope.interfaceInterval = setInterval(function () {
        realLog();
        schedule(installingPkg);
      }, 2000)
    } else {
      realLog();
      schedule();
      $scope.interfaceInterval = setInterval(function () {
        realLog();
        schedule();
      }, 2000)
    }
  }

  //结束安装
  function stopInstall() {
    $scope.installing = false;
    $scope.isContinue = false;
    $scope.installingPkg = "";
    $scope.installingSql = "";

    //结束轮询
    clearInterval($scope.interfaceInterval);

    realLog();
    init();
  }

  //暂停安装
  function pauseInstall() {
    //结束轮询
    clearInterval($scope.interfaceInterval);
  }

  //继续安装
  function continueInstall() {
    $scope.isContinue = true;
    if ($scope.continueType.isAll) {
      //一键安装
      $scope.oneKey();
    } else if ($scope.continueType.isPackage) {
      //单个包安装
      $scope.onePackage($scope.continueType.index);
    } else {
      //单个安装
      $scope.oneSql($scope.continueType.packageName, $scope.continueType.sqlName);
    }
  }

  //实时日志查询
  function schedule(installingPkg) {
    var temp = installingPkg ? ("/package?packageName=" + installingPkg) : "";
    $http.get('/deploy/install/interface/schedule' + temp).then(function (response) {
      var message = response.data.data;
      $scope.sqlListPkgs = message.interfaces;
      changeInstall(message.targetPackage.name, message.targetSql.name);
    }).catch(function (response) {
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  }

  //实时日志查询
  var p = 0;

  function realLog() {
    $http.post('/deploy/install/interface/real/log', {
      pos: p
    }).then(function (response) {
      var message = response.data;
      if (message.code == 0) {
        p = message.data.pos;
        //更新日志数据
        $scope.runLogs = $scope.runLogs.concat(message.data.log);

        //判断日志的滚动条是否在底部
        var all = $("#installInterface-log .console")[0].scrollHeight;
        var top = $("#installInterface-log .console")[0].scrollTop;
        var height = $("#installInterface-log .console").height();
        var flag = (top + height + 19 <= all || top + height + 21 >= all);
        //如果之前日志的滚动条在底部则保持在底部
        if (flag)
          setTimeout(function () {
            $("#installInterface-log .console")[0].scrollTop = $("#installInterface-log .console")[0].scrollHeight;
          }, 0);
      } else {
        $.showNotice(message.msg, "danger");
      }
    }).catch(function (response) {
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  }

  //查看注意事项
  function getReadme(version) {
    function isArray(o) {
      return Object.prototype.toString.call(o) == '[object Array]';
    }

    var postData = isArray(version) ? version : new Array(version);
    $('#installInterface-notice').modal('show');
    $http.post('/deploy/install/interface/readme', postData).then(function (response) {
      if (response.status == 200) {
        var message = response.data;
        if (message.code == 0) {
          $scope.readme = message.data[0].remark;
        } else {
          $.showNotice(message.msg, "danger");
        }
      }
    }).catch(function (response) {
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  }

  //改变checkbox
  $scope.changeCheckbox = function (isPkg) {
    if (isPkg)
      for (var i in $scope.sqlListPkgs)
        for (var j in $scope.sqlListPkgs[i].sqlList)
          $scope.sqlListPkgs[i].sqlList[j].checked = $scope.sqlListPkgs[i].checked;
    else
      for (var i in $scope.sqlListPkgs) {
        var flag = true;
        for (var j in $scope.sqlListPkgs[i].sqlList) {
          if (!$scope.sqlListPkgs[i].sqlList[j].checked) {
            flag = false;
            break;
          }
        }
        $scope.sqlListPkgs[i].checked = flag;
      }
  };

  //一键安装
  $scope.oneKey = function (isAll) {
    $scope.exAll();

    //如果是安装所有则全部置为未安装状态
    if (isAll)
      for (var i in $scope.sqlListPkgs) {
        $scope.sqlListPkgs[i].checked = false;
        for (var j in $scope.sqlListPkgs[i].sqlList)
          $scope.sqlListPkgs[i].sqlList[j].checked = false;
      }

    $http.post('/deploy/install/interface/oneKeySetup', $scope.sqlListPkgs).then(function (response) {

      var message = response.data;
      if (message.code == 0) {
        stopInstall();
        $.showNotice(message.msg);
        //注意事项
        var version = [];
        for (var i in $scope.sqlListPkgs)
          version.push($scope.sqlListPkgs[i].version);
        getReadme(version);
      } else if (message.code == 1) {
        pauseInstall();
        $('#installInterface-manger').modal('show');
        $scope.errSql = message.data;
        $scope.continueType = {
          isAll: true
        }
      } else if (message.code == 2) {
        pauseInstall();
        $('#installInterface-confirm').modal('show');
        $scope.errSql = message.data;
        $scope.continueType = {
          isAll: true
        }
      } else {
        stopInstall();
        $.showNotice(message.msg, "danger");
      }
    }).catch(function (response) {
      stopInstall();
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
    startInstall();
  };

  //单独安装
  $scope.onePackage = function (index) {
    //展开
    $scope.collapse[index] = true;

    $http.post('/deploy/install/interface/onePackage', $scope.sqlListPkgs[index]).then(function (response) {
      var message = response.data;
      if (message.code == 0) {
        stopInstall();
        if ($scope.sqlListPkgs[index].checked)
          $.showNotice("无需安装，如需重新安装请先取消【已全部安装】勾选", "danger");
        else
          $.showNotice(message.msg);
      } else if (message.code == 1) {
        pauseInstall();
        $('#installInterface-manger').modal('show');
        $scope.errSql = message.data;
        $scope.continueType = {
          isPackage: true,
          index: index
        }
      } else if (message.code == 2) {
        pauseInstall();
        $('#installInterface-confirm').modal('show');
        $scope.errSql = message.data;
        $scope.continueType = {
          isPackage: true,
          index: index
        }
      } else if (message.code == 3) {
        pauseInstall();
        $('#installInterface-version').modal('show');
        $scope.errSql = message.data;
        $scope.isPlatform = false;
        $scope.continueType = {
          isPackage: true,
          index: index
        }
      } else if (message.code == 4) {
        pauseInstall();
        $('#installInterface-confirm').modal('show');
        $scope.errSql = message.data;
        $scope.isPlatform = true;
        $scope.continueType = {
          isPackage: true,
          index: index
        }
      } else {
        stopInstall();
        $.showNotice(message.msg);
      }

    }).catch(function (response) {
      stopInstall();
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
    startInstall($scope.sqlListPkgs[index].name, "", false, true);
  };

  //单独安装
  $scope.oneSql = function (packageName, sqlName, tips) {
    $http.post('/deploy/install/interface/oneSql', {
      packageName: packageName,
      sqlName: sqlName
    }).then(function (response) {
      stopInstall();
      var message = response.data;
      if (message.code == 0) {
        $.showNotice(message.msg);
        //判断是否需要弹出注意事项
        $http.get('/deploy/install/interface/init').then(function (response) {
          if (response.status == 200) {
            var message = response.data;
            if (message.code == 0) {
              for (var i in message.data)
                if (message.data[i].name == packageName && message.data[i].checked == true) {
                  var version = message.data[i].version;
                  //注意事项
                  getReadme(version);
                }
            } else {
              $.showNotice(message.msg, "danger");
            }
          }
        }).catch(function (response) {
          $.showNotice(response.status + " error：" + response.data.message, "danger");
        });
      } else if (message.code == 1) {
        pauseInstall();
        $('#installInterface-manger').modal('show');
        $scope.errSql = message.data;
        $scope.continueType = {
          isPackage: false,
          packageName: packageName,
          sqlName: sqlName
        }
      } else {
        $.showNotice(message.msg, "danger");
      }
    }).catch(function (response) {
      stopInstall();
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
    startInstall(packageName, sqlName, true);
  };

  //查看日志
  $scope.getLog = function (packageName, sqlName, tips) {
    $http.post('/deploy/install/interface/log', {
      packageName: packageName,
      sqlName: sqlName
    }).then(function (response) {
      if (response.data.code == 0) {
        $('#installInterface-console').modal('show');
        $scope.logs = response.data.data;
      } else
        $.showNotice(response.data.msg, "danger");
    }).catch(function (response) {
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  };

  //权限验证
  $scope.setManager = function (manager) {
    if (!manager || !Trim(manager.manager, true)) {
      $.showNotice("用户名不能为空", "danger");
      return;
    }
    if (!manager.password || !Trim(manager.password, true)) {
      $.showNotice("密码不能为空", "danger");
      return;
    }
    $scope.setManagerFlag = true;
    $http.post('/deploy/install/interface/set/manager', manager).then(function (response) {
      if (response.status == 200) {
        $scope.setManagerFlag = false;
        var message = response.data;
        if (message.code == 0) {
          $('#installInterface-manger').modal('hide');
          $.showNotice(message.msg, "info");
          continueInstall();
        } else {
          $.showNotice(message.msg, "danger");
        }
      }
    }).catch(function (response) {
      $scope.setManagerFlag = false;
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  };
  //停止安装
  $scope.stopManager = stopInstall;
  // 已手动执行
  $scope.yesManager = function () {
    $('#installInterface-manger').modal('hide');
    //跳过错误sql
    for (var i in $scope.sqlListPkgs) {
      if ($scope.sqlListPkgs[i].name == $scope.errSql.packageName) {
        for (var j in $scope.sqlListPkgs[i].sqlList) {
          if ($scope.sqlListPkgs[i].sqlList[j].name == $scope.errSql.sqlName)
            $scope.sqlListPkgs[i].sqlList[j].checked = true;
        }
      }
    }
    if ($scope.continueType.isPackage)
      continueInstall();
    else { }
  }

  //确认备份并继续安装
  $scope.confirmYes = function () {
    $('#installInterface-confirm').modal('hide');
    //跳过错误sql
    for (var i in $scope.sqlListPkgs) {
      if ($scope.sqlListPkgs[i].name == $scope.errSql.packageName) {
        for (var j in $scope.sqlListPkgs[i].sqlList) {
          if ($scope.sqlListPkgs[i].sqlList[j].name == $scope.errSql.sqlName)
            $scope.sqlListPkgs[i].sqlList[j].checked = true;
        }
      }
    }
    continueInstall();
  };
  // 重新备份并继续安装
  $scope.confirmBackup = function () {
    // 删除旧备份并重新备份
    $http.post('/deploy/install/interface/delete/backup', {
      packageName: $scope.errSql.packageName
    }).then(function (response) {
      if (response.status == 200) {
        $scope.setManagerFlag = false;
        var message = response.data;
        if (message.code == 0) {
          $('#installInterface-confirm').modal('hide');
          continueInstall();
        } else {
          $.showNotice(message.msg, "danger");
        }
      }
    }).catch(function (response) {
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  };
  // 没有备份并停止安装
  $scope.confirmNo = stopInstall;

  // 确认版本并继续安装
  $scope.versionYes = function () {
    $('#installInterface-version').modal('hide');

    //跳过错误sql
    for (var i in $scope.sqlListPkgs) {
      if ($scope.sqlListPkgs[i].name == $scope.errSql.packageName) {
        for (var j in $scope.sqlListPkgs[i].sqlList) {
          if ($scope.sqlListPkgs[i].sqlList[j].name == $scope.errSql.sqlName)
            $scope.sqlListPkgs[i].sqlList[j].checked = true;
        }
      }
    }
    continueInstall();
  };
  //没有备份并停止安装
  $scope.versionNo = stopInstall;

  //提交
  $scope.submitFnc = function () {
    $location.path('platform');
    /*if ($scope.loadingNext) return;
    $scope.loadingNext = true;

    $http.post('/deploy/install/interface/submit').then(function (response) {
      if (response.status == 200) {
        var message = response.data;
        if (message.code == 0) {
          $location.path('platform');
        } else {
          $scope.loadingNext = false;
          $.showNotice(message.msg, "danger");
        }
      }
    }).catch(function (response) {
      $scope.loadingNext = false;
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });*/
  };

  //导入安装包
  $scope.importInstall = function () {
    $http.get('/deploy/install/db/importPackages/2').then(function (response) {
      var rowData = response.data.data;
      var data = [];
      for (var i in rowData) {
        var isNew = true;
        for (var j in $scope.sqlListPkgs) {
          if (rowData[i].substr(0, rowData[i].lastIndexOf(".")) == $scope.sqlListPkgs[j].name) {
            isNew = false;
          }
        }
        if (isNew) data.push(rowData[i]);
      }
      $scope.importPkgs = data;
      $('#installInterface-import-dialog').modal('show');
    }).catch(function (response) {
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  };

  $scope.addPkgs = [];
  $scope.addImports = function (pkg) {
    var index = $scope.addPkgs.indexOf(pkg);
    if (index == -1) {
      $scope.addPkgs.push(pkg);
    } else {
      $scope.addPkgs.splice(index, 1);
    }
  }

  $scope.addImport = function () {
    $scope.importing = true;
    $http.post('/deploy/install/interface/import', {
      fileName: $scope.addPkgs
    }).then(function (response) {
      $scope.importing = false;
      if (response.status == 200) {
        var message = response.data;
        if (message.code == 0) {
          $.showNotice(message.msg, "success");
          $('#installInterface-import-dialog').modal('hide');
          init();
        } else {
          $.showNotice(message.msg, "danger");
        }
      }
    }).catch(function (response) {
      $scope.importing = false;
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  };

  //删除安装包
  $scope.delPkg = function (name) {
    if (confirm("确认删除：" + name)) {
      $http.post('/deploy/install/interface/del/package', {
        name: name
      }).then(function (response) {
        if (response.status == 200) {
          var message = response.data;
          if (message.code == 0) {
            $.showNotice(message.msg, "success");
            init();
          } else {
            $.showNotice(message.msg, "danger");
          }
        }
      }).catch(function (response) {
        $.showNotice(response.status + " error：" + response.data.message, "danger");
      });
    }
  };

  //清空安装包
  $scope.delPkgs = function () {
    if (confirm("确认清空所有安装包？")) {
      $http.post('/deploy/install/interface/del/packages').then(function (response) {
        if (response.status == 200) {
          var message = response.data;
          if (message.code == 0) {
            $.showNotice(message.msg, "success");
            init();
          } else {
            $.showNotice(message.msg, "danger");
          }
        }
      }).catch(function (response) {
        $.showNotice(response.status + " error：" + response.data.message, "danger");
      });
    }
  };


  //查看编译失效对象
  $scope.$watch('sqlListPkgs', function () {
    $scope.compileFlag = $scope.sqlListPkgs && $scope.sqlListPkgs.length > 0 ? true : false;
    for (var i in $scope.sqlListPkgs) {
      for (var j in $scope.sqlListPkgs[i].sqlList) {
        if (!$scope.sqlListPkgs[i].sqlList[j].checked)
          $scope.compileFlag = false;
      }
    }
  }, true);

  function getCompileItems() {
    $http.get('/deploy/install/interface/compile?pageNo=' + ($scope.nowPage - 1) + '&pageSize=10').then(function (response) {
      var message = response.data;
      $scope.pages = [];
      for (var i = 0; i < message.data.pages; i++)
        $scope.pages.push(i + 1);
      $scope.compileItems = message.data.items;
      $scope.compileItemsTotal = message.data.total;
    }).catch(function (response) {
      $.showNotice(response.status + " error：" + response.data.message, "danger");
    });
  }

  $scope.compileDialog = function () {
    $('#installInterface-compile-dialog').modal('show');
    //分页
    $scope.nowPage = 1;
    getCompileItems();

    //切换分页并处理分页位置
    var cal = 8;
    $scope.calPage1 = 0;
    $scope.calPage2 = cal - $scope.calPage1;
    $scope.changePage = function (page) {
      if (page > 0 && page < $scope.pages.length + 1) {
        $scope.nowPage = page;
        getCompileItems();
        if (page <= cal / 2 + 1) {
          $scope.calPage1 = page - 1;
          $scope.calPage2 = cal - page + 1;
        } else if (page >= $scope.pages.length - cal / 2) {
          $scope.calPage2 = $scope.pages.length - page;
          $scope.calPage1 = cal + page - $scope.pages.length;
        } else {
          $scope.calPage1 = cal / 2;
          $scope.calPage2 = cal / 2;
        }
      }
    };

  };

});